package com.qupeng.demo.kafka.kafkaapache.security;

import org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder;
import org.apache.kafka.common.security.kerberos.KerberosShortNamer;
import org.apache.kafka.common.security.ssl.SslPrincipalMapper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserCertSubjectPrincipalBuilder extends DefaultKafkaPrincipalBuilder {
    public static final String DEFAULT_MAPPER_RULE = "RULE:([cC][nN]=.*?),O=io.strimzi.*$/$1,O=io.strimzi/,RULE:([cC][nN]=.*?),([a-zA-Z]{1,2})=.*$/$1/,DEFAULT";

    public UserCertSubjectPrincipalBuilder() {
        super(null, new SslPrincipalMapper("RULE:([cC][nN]=.*?),O=io.strimzi.*$/$1,O=io.strimzi/,RULE:([cC][nN]=.*?),([a-zA-Z]{1,2})=.*$/$1/,DEFAULT"));
    }

    public UserCertSubjectPrincipalBuilder(KerberosShortNamer kerberosShortNamer, SslPrincipalMapper sslPrincipalMapper) {
        super(kerberosShortNamer, new SslPrincipalMapper("RULE:([cC][nN]=.*?),O=io.strimzi.*$/$1,O=io.strimzi/,RULE:([cC][nN]=.*?),([a-zA-Z]{1,2})=.*$/$1/,DEFAULT"));
    }

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("([cC][nN]=.*?),O=io.strimzi.*/$1,O=io.strimzi/");
        Matcher matcher = pattern.matcher("CN=msghub-sdf,O=io.strimzi");
        if (matcher.matches()) {
            System.out.println(matcher.group(1));
        }
    }
}